var home = require("../../utils/util.js");
var url = home.home;
var url2 = home.home2;
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeNames: [],
    type: 1,
    videoData: {
      direction: -90,
      show_mute_btn: true,
      vslide_gesture: false,
      page_gesture: false,
    },
    vipId: '',
    guestData: [], //优惠券列表数据
    tokerData: {}, //贵宾卡数据
    show5: false,
    shopData: {},
    storeId: app.globalData.storeId,
    toReceiveVipId: '',
    states:0,
    memberId: home.getKey('userId'),
    phone: home.getKey('phone'),
    loadState: true,
    bgcolor: home.getKey('bgcolor') == '' ? 'ff7711' : home.getKey('bgcolor'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let scene = decodeURIComponent(options.scene);
    let type1 = options.type;
    if (options.type == 4 || options.type == 5) {
      type1 = 2;
    }
    if (options.type == 6) {
      type1 = 3;
    }
    if (scene != 'undefined') {
      let arr = scene.split('&');
      let arr1 = arr[0];
      let arr2 = arr[1];
      let vipId = arr1.split('=')[1];
      let type = arr2.split('=')[1];
      options.id = vipId;
      options.type = type;
      type1 = type;
    }
    this.setData({
      type: options.type == 6 ? 3 : options.type,
      vipId: options.id ? options.id : options.vipId,
      type1: type1
    });
  },

  //获取贵宾卡信息
  getGuestInfo() {
    let that = this;
    wx.request({
      url: url + 'app/getVipDetail?vipId=' + that.data.vipId + '&type=' + that.data.type,
      data: {
        vipId: that.data.vipId,
        type: that.data.type1
      },
      method: 'GET',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          if (!res.data.result.shareNum) {
            res.data.result.shareNum = res.data.result.num
          }
          for (let i = 0; i < res.data.result.couponList.length; i++) {
            res.data.result.couponList[i].types = 2;
            if (res.data.result.couponList[i].videos) {
              if (res.data.result.couponList[i].videos.indexOf('mp4') > -1 || res.data.result.couponList[i].videos.indexOf('MP4') > -1) {
                res.data.result.couponList[i].types = 1;
                res.data.result.couponList[i].videos = 'https://kyz.fbhkj.com//' + res.data.result.couponList[i].videos;
              } else {
                res.data.result.couponList[i].videos = 'https://kyz.fbhkj.com//' + res.data.result.couponList[i].videos;
              }
            }
          }
          that.setData({
            tokerData: res.data.result,
            guestData: res.data.result.couponList,
            storeId: res.data.result.card['storeId'],//王重阳关闭
          });
          home.setKey('storeId', res.data.result.card['storeId']);//王重阳关闭
        } else {
          home.wxMessage('参数错误', 'none');
        }
      }
    })
  },

  //获取店铺信息
  getShop() {
    let that = this;
    wx.request({
      url: url + 'app/getStore',
      data: {
        storeId: that.data.storeId
      },
      method: 'GET',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          res.data.result.storeCity = res.data.result.storeCity.split(",");
          res.data.result.storeCity = res.data.result.storeCity.join('');
          res.data.result.address = res.data.result.storeCity + res.data.result.storeAddress;
          that.setData({
            shopData: res.data.result,
          })
        } else {
          wx.showToast({
            title: '店铺信息获取失败',
            icon: 'none'
          })
        }
      }
    })
  },

  register() {
    let that = this;
    wx.login({
      success: function name(res) {
        let data = {};
        data.code = res.code;
        data.storeId = that.data.storeId;
        if (that.data.type == 3 || that.data.type == 4) {
          data.loginType = 2;
        }
        console.log(data);
        wx.request({
          url: url + 'app/xcx/register?storeId=' + app.globalData.storeId + '&code=' + res.code,
          data: data,
          method: 'POST',
          header: {
            "content-type": "application/json", // 默认
          },
          success: function (rea) {
            if (rea.data.code == 200) {
              let states = 2;
              if (!rea.data.result.hasPhone) {
                states = 0;
              }
              home.setKey('hasNickName', rea.data.result.hasNickName);
              home.setKey('hasPhone', rea.data.result.hasPhone);
              home.setKey('userId', rea.data.result.member.id);
              home.setKey('phone', rea.data.result.member.phone);
              home.setKey('avatar', rea.data.result.member.avatarUrl);
              home.setKey('status', rea.data.result.member.status);
              home.setKey('discount', rea.data.result.member.discount);
              home.setKey('nickName', rea.data.result.member.nickName);
              home.setKey('openId', rea.data.result.member.xcxOpenId);
              home.setKey('unionId', rea.data.result.member.unionId);
              that.setData({
                states: states,
                memberId: rea.data.result.member.id,
                phone: rea.data.result.member.phone
              });
              wx.hideLoading({
                success: (res) => {
                  that.setData({
                    loadState:false,
                  })
                },
              })
            } else {
              home.wxMessage(rea.data.message,'none');
            }
          }
        })
      }
    })
  },

  //获取手机号
  getPhoneNumber(e) {
    if (e.detail.code == undefined) {
      home.wxMessage('请授权获取手机号', 'none');
      wx.setStorageSync('state', 1);
      return false;
    }
    let that = this;
    wx.request({
      url: 'https://kyz.fbhkj.com/fubaihui/app/xcx/getPhone?storeId=' + app.globalData.storeId + '&code=' + e.detail.code + '&xcxOpenId=' + wx.getStorageSync('openId') + '&unionId=' + wx.getStorageSync('unionId'),
      data: {
        storeId: app.globalData.storeId,
        code: e.detail.code,
        xcxOpenId: wx.getStorageSync('openId'),
        unionId: wx.getStorageSync('unionId')
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          home.setKey('userId',res.data.result.id);
          that.setData({
            states: 2,
            memberId: res.data.result.id
          })
        } else {
          home.wxMessage('授权失败', 'none');
        }
      }
    })
  },

  getShareId() {
    let that = this;
    wx.request({
      url: url + 'app/shareVip',
      data: {
        shareVipId: that.data.vipId,
        storeId: app.globalData.storeId,
        memberId: that.data.memberId,
        type: '2'
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          that.setData({
            toReceiveVipId: res.data.result.toReceiveVipId,
          });
          that.receive();
        } else {
          home.wxMessage('领取失败', 'none');
        }
      }
    })
  },

  receive1() {
    if (this.data.type == 3) {
      this.receive();
    } else {
      this.getShareId();
    }
  },

  //领取贵宾卡
  receive() {
    let that = this;
    let tokerData = that.data.tokerData;
    let toReceiveVipId = that.data.toReceiveVipId;
    if (this.data.type == 3) {
      toReceiveVipId = this.data.vipId;
    }
    wx.request({
      url: url + 'app/receiveVip',
      data: {
        memberId: home.getKey('userId'),
        storeId: home.getKey('storeId'),
        toReceiveVipId: toReceiveVipId,
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          if (res.data.result.payParams != null) {
            wx.requestPayment({
              "timeStamp": res.data.result.payParams.timeStamp,
              "nonceStr": res.data.result.payParams.nonceStr,
              "package": res.data.result.payParams.package_str,
              "signType": res.data.result.payParams.signType,
              "paySign": res.data.result.payParams.paySign,
              "success": function (res) {
                if (res.errMsg == 'requestPayment:ok') {
                  tokerData.shareNum -= 1;
                  that.setData({
                    tokerData: tokerData
                  });
                  home.wxMessage('领取成功,跳转首页', 'none');
                  setTimeout(function () {
                    wx.reLaunch({
                      url: '../../pages/index/index',
                    })
                  }, 1500);
                }
              },
              "fail": function (res) {
                wx.showToast({
                  title: '取消支付',
                  icon: 'none'
                });
                return false;
              },
              "complete": function (res) {}
            })
          } else {
            tokerData.shareNum -= 1;
            that.setData({
              tokerData: tokerData
            });
            home.wxMessage('领取成功,跳转首页', 'none');
            setTimeout(function () {
              wx.reLaunch({
                url: '../../pages/index/index',
              })
            }, 1500);
          }
        } else {
          home.wxMessage(res.data.message, 'none');
          setTimeout(function () {
            wx.reLaunch({
              url: '../../pages/index/index',
            })
          }, 500);
        }
      }
    })
  },

  /**
   * 折叠面板
   */
  onChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },

  /**
   * 调起手机拨号 
   */
  callPhone() {
    let shopData = this.data.shopData;
    wx.makePhoneCall({
      phoneNumber: shopData.storePhone // 仅为示例，并非真实的电话号码
    })
  },

  /**
   * 打开地图
   */
  // openMap() {
  //   let shopData = this.data.shopData;
  //   wx.getLocation({
  //     type: 'gcj02', //返回可以用于wx.openLocation的经纬度
  //     success(res) {
  //       const latitude = shopData.lat //目标纬度
  //       const longitude = shopData.lng //目标经度
  //       wx.openLocation({
  //         latitude,
  //         longitude,
  //         scale: 18
  //       })
  //     }
  //   })
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      memberId: home.getKey('userId'),
      storeId: app.globalData.storeId,
      phone: home.getKey('phone'),
      loadState: true
    })
    this.getShop();
    this.getGuestInfo();
    this.register();
    wx.showLoading({
      title: '加载中...',
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})